package com.woate.wingframework.utils;

import java.util.Random;

/**
 * 使用时间戳和随机数字构成无重复的特定字符串
 * 13位为时间毫秒数，2位为服务器编号，3位线程号，2位随机号
 */
public class TimeMillisSequenceHandler implements SequenceHandler {
    public String nextId(int sid, int tid, SequenceStyle style) {
        long timestamp = this.timeGen();
        int random;
        if (style.getRandom() == 2) {
            random = Math.abs(new Random().nextInt(99));
        } else if (style.getRandom() == 3) {
            random = Math.abs(new Random().nextInt(999));
        } else if (style.getRandom() == 4) {
            random = Math.abs(new Random().nextInt(9999));
        } else {
            random = Math.abs(new Random().nextInt(9));
        }
        return truncateOrFill(String.valueOf(timestamp), false, '0', style.getTimeMillis()) + truncateOrFill(String.valueOf(sid), false, '0', style.getServerId()) + truncateOrFill(String.valueOf(tid), false, '0', style.getThreadId()) + fill(String.valueOf(random), false, '0', style.getRandom());
    }

    String truncate(String in, boolean rightStyle, int len) {
        String str = in;
        int infactLen = str.length();
        if (infactLen > len) {
            if (rightStyle) {
                str = str.substring(0, len);
            } else {
                str = str.substring(infactLen - len);
            }
        }
        return str;
    }

    String fill(String in, boolean rightStyle, char fillChar, int len) {
        String str = in;
        while (str.length() < len) {
            str = rightStyle ? str + fillChar : fillChar + str;
        }
        return str;
    }

    String truncateOrFill(String in, boolean rightStyle, char fillChar, int len) {
        if (in.length() > len) {
            return truncate(in, rightStyle, len);
        } else if (in.length() < len) {
            return fill(in, rightStyle, fillChar, len);
        } else {
            return in;
        }
    }

    long timeGen() {
        return System.currentTimeMillis();
    }
}
